package com.sansecy.progressbar;


import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.Nullable;

import java.util.Calendar;

/**
 * @Description TODO
 * @Date 2019-08-09 06:18
 * @Created by caoyu
 */
public class SunriseView extends View {
    private static final String TAG = "SunriseView-App";
    private Paint mBorderPaint;
    private DashPathEffect mDashPathEffect;
    private RectF mRectF;
    private int mSweepAngle;
    private Bitmap mSun;
    private Point mPoint;
    private float mSunDegree;
    private int mStartPoint;
    private int mEndPoint;
    private int mCurrentPoint;
    private int mContentWidth;
    private int mContentHeight;
    private float mRadiusRatio;
    private int mMeasuredWidth;
    private int mRadius;
    private int mPaddingLeft;
    private int mPaddingRight;

    public SunriseView(Context context) {
        this(context, null);
    }

    public SunriseView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        mBorderPaint = new Paint();
        mBorderPaint.setStrokeWidth(4);
        mBorderPaint.setColor(Color.WHITE);
        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setAntiAlias(true);
        mDashPathEffect = new DashPathEffect(new float[]{5, 5}, 0);

//        mOrbitPaint = new Paint();
//        mOrbitPaint.setStrokeWidth(4);
//        mOrbitPaint.setColor(Color.WHITE);
//        mOrbitPaint.setStyle(Paint.Style.STROKE);
//        mOrbitPaint.setAntiAlias(true);
        mRectF = new RectF();

        mRadiusRatio = 0.8f;
        //左侧比例
        //右侧比例

        mSweepAngle = 180;

        mSun = BitmapFactory.decodeResource(getResources(), R.drawable.ic_sun);
        mPoint = new Point();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //宽度和高度必须要成比例

        //需要根据宽度来确定高度
        //先测量宽度

        mMeasuredWidth = measureWidth(widthMeasureSpec);
        int measuredHeight = measureHeight(heightMeasureSpec);

        //圆点坐标是宽度的一半
        mPoint.x = mContentWidth / 2 + mPaddingLeft;
        mPoint.y = mContentHeight + getPaddingTop();


        int left = mPoint.x - mRadius;
        int top = mPoint.y - mRadius;
        int right = mPoint.x + mRadius;
        int bottom = mPoint.y + mRadius;
        mRectF.set(left, top, right, bottom);

        setMeasuredDimension(mMeasuredWidth, measuredHeight);
    }

    private int measureWidth(int measureSpec) {
//        return resolveSizeAndState(size, measureSpec, 0);
        int result;
        mPaddingLeft = getPaddingLeft();
        mPaddingRight = getPaddingRight();
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
            //我们的视图必须尊重填充
            //如果使用了PaddingStart和PaddingEnd，将覆盖上面的属性
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (getPaddingStart() > 0) {
                    mPaddingLeft = getPaddingStart();
                }
                if (getPaddingEnd() > 0) {
                    mPaddingRight = getPaddingEnd();
                }
            }
        } else {
            //因为我们的视图主要是一个宽长高短的视图
            //所以默认情况下让它遵从父级的指定的宽度
            result = specSize;
        }
        mContentWidth = specSize - mPaddingLeft - mPaddingRight;

        return result;
    }

    private int measureHeight(int measureSpec) {
        int result;

        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
            //我们的视图必须尊重填充
            mContentHeight = specSize - getPaddingTop() - getPaddingBottom();
        } else {
            //因为我们的视图主要是一个宽长高短的视图
            //所以高度必须按照宽度来计算
            int halfWidth = mContentWidth / 2;
            //根据设定好的半径占宽度的内容的比例获得半径
            mRadius = (int) (halfWidth * mRadiusRatio);
            //半径作为高度
            result = mRadius;
        }
        mContentHeight = result - getPaddingTop() - getPaddingBottom();
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int height = getHeight();
        //画出底部线
        canvas.drawLine(mPaddingLeft, height, mContentWidth + mPaddingLeft, height, mBorderPaint);
//        canvas.drawLine(getWidth() - mPaddingRight, 0, getWidth() - mPaddingRight, height, mBorderPaint);

        mBorderPaint.setPathEffect(mDashPathEffect);

        float x = (float) (mPoint.x + mRadius * Math.cos(-(180 - mSunDegree) * Math.PI / 180));
        float y = (float) (mPoint.y + mRadius * Math.sin(-(180 - mSunDegree) * Math.PI / 180));
        canvas.drawBitmap(mSun, x - (float) mSun.getWidth() / 2, y - (float) mSun.getHeight() / 2, mBorderPaint);
        canvas.drawArc(mRectF, -180, mSweepAngle, false, mBorderPaint);
//        canvas.drawCircle(mPoint.x, mPoint.y, mRadius, mBorderPaint);
//        canvas.drawRect(mRectF, mBorderPaint);
    }

    public void start() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(this.mStartPoint, mCurrentPoint);
        valueAnimator.setDuration(3000);
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                Log.d(this.getClass().getName(), "onAnimationUpdate: " + value);
                setProgress(value);
            }
        });
        valueAnimator.start();
    }

    private void setProgress(float progress) {
        if (progress < mStartPoint) {
            progress = mStartPoint;
        } else if (progress > mEndPoint) {
            progress = mEndPoint;
        }
        mSunDegree =(int) (180 * (progress / mEndPoint));
        Log.d(this.getClass().getName(), "setProgress: " + mSunDegree);
        invalidate();
    }

    public static int geTimePoint(String time) {
        String[] split = time.split(":");

        int startHour = 0;
        int startMinute = 0;

        if (split.length >= 1) {
            startHour = Integer.valueOf(split[0]);
            startMinute = Integer.valueOf(split[1]);
        }
        return (startHour * 60 + startMinute) * 60;
    }

    /**
     * 时间统一转换成分
     *
     * @param sunriseTime 日出时间
     * @param sunsetTime  日落时间
     */
    public void setTime(String sunriseTime, String sunsetTime) {
        mStartPoint = geTimePoint(sunriseTime);
        int offset = mStartPoint;
        //让起始点为0,易于计算
        mStartPoint = 0;
        //mEndPoint同理
        mEndPoint = geTimePoint(sunsetTime) - offset;

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        mCurrentPoint = (hour * 60 + minute) * 60 + second - offset;
    }
}
